-- 模块导入
local template = require('resty.template')
local common = require('common')
local cjson = require('cjson')
local read_redis = common.read_redis
local read_http = common.read_http
local read_data = common.read_data
local read_cache = common.read_cache

-- 获取spuId这个变量
local spuId = ngx.var.spuId

local ip = '127.0.0.1'
local port = 6379
-- 查询数据（先查询redis、如果失败，再查询tomcat）
-- 1.查询spu
local key = "page:spu:id:"..spuId
local path = "/spu/"..spuId
local spu_info_str = read_data(ip, port, key, path, {})
if not spu_info_str then
  -- 商品不存在
  ngx.exit(404)
end
-- 2.查询sku
local key = "page:sku:id:"..spuId
local path = "/sku/"..spuId
local sku_info_str = read_data(ip, port, key, path, {})
if not sku_info_str then
  -- 商品不存在
  ngx.exit(404)
end
-- 3.查询spuDetail
local key = "page:detail:id:"..spuId
local path = "/detail/"..spuId
local detail_info_str = read_data(ip, port, key, path, {})
if not detail_info_str then
  -- 商品不存在
  ngx.exit(404)
end
-- 4.查询分类
-- 4.1.把spu json 转table
local spu = cjson.decode(spu_info_str)
-- 4.2.获取spu中的分类id集合
local ids = spu.categoryIds;
local key = "page:category:id:"..ids[3]
local path = "/categories"
local category_info_str = read_cache(ip, port, key, path, {ids=table.concat(ids, ",")})
if not category_info_str then
  -- 商品不存在
  ngx.exit(404)
end
-- 5.查询brand
local key = "page:brand:id:"..spu.brandId
local path = "/brand/"..spu.brandId
local brand_info_str = read_cache(ip, port, key, path, {})
if not brand_info_str then
  -- 商品不存在
  ngx.exit(404)
end
-- 6.查询spec
local key = "page:spec:id:"..ids[3]
local path = "/spec/"..ids[3]
local spec_info_str = read_cache(ip, port, key, path, {})
if not spec_info_str then
  -- 商品不存在
  ngx.exit(404)
end
-- 模板数据
local data = {
    name = spu.name, -- 商品spu的name
    skuList = sku_info_str, -- spu下的所有sku
    categories = category_info_str, -- spu相关的三级分类
    brand = brand_info_str, -- spu相关的品牌
    detail = detail_info_str, -- spu的detail
    specs = spec_info_str, -- spu有关的商品分类的规格组合规格参数
}
-- 模板渲染
template.render("item.html", data)